package com.bhs.sansong.net;


import com.bhs.sansong.base.MyApplication;
import com.bhs.sansong.utils.LogUtils;
import com.bhs.sansong.utils.SharedPreferencesUtils;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Connection;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class LoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        final Charset UTF8 = Charset.forName("UTF-8");

        Connection connection = chain.connection();
        Request request2 = chain.request();



        //headers.put("version-int", Config.version_int + "");
        //        headers.put("device-type", "ANDROID");
        Request request =  addPostBaseParams(request2);
        Response response = chain.proceed(request);


        RequestBody requestBody = request.body();
        String requestStartMessage = "--> "
                + request.method()
                + ' ' + request.url()
                + (connection != null ? " " + connection.protocol() : "");
        LogUtils.d("netWork","请求"+requestStartMessage);

        Buffer buffer = new Buffer();
        MediaType contentType=null;
        Charset charset = UTF8;
        if(requestBody!=null){
            requestBody.writeTo(buffer);
            contentType = requestBody.contentType();
        }
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        LogUtils.d("netWork","提交的参数-->"+buffer.readString(charset));

        LogUtils.d("netWork","结果-->"+response.code()
                + (response.message().isEmpty() ? "" : ' ' + response.message())
                + ' ' + response.request().url());

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer1 = source.buffer();
        if (contentLength != 0) {
            LogUtils.d("netWork","返回的数据-->"+buffer1.clone().readString(charset));
        }

        return response;
    }


    private Request addPostBaseParams(Request request) {

        HttpUrl httpUrl = request.url()
                .newBuilder()
                .addQueryParameter("login_token", SharedPreferencesUtils.getString(MyApplication.getContext(), "token"))
                .build();//平台号
        request = request.newBuilder().url(httpUrl).build();
        return request;
    }



}
